(function (jQuery) {
    //渲染dom树的代码
    function getStr(ele) {
        let str = `
            <div class="good">
                            <dl>
                                <dt><input type="checkbox"></dt>
                                <dd>
                                    <span><a href="#"><img src=${ele.img} alt=""></a></span>
                                    <span class="right">
                                        <p class="description"><a href="#"> ${ele.goodName}（${ele.gid})</a></p>
                                        <p class="brief">品牌：梦芭莎　尺寸：${ele.size}　颜色：${ele.color} </p>
                                    </span>
                                </dd>
                                <dd>
                                    <span>¥${ele.price}</span>
                                </dd>
                                <dd>
                                    <a href="javascript:void(0)" class="minus">-</a>
                                    <input id="good_num" type="text" class="num" value=${ele.num}>
                                    <a href="javascript:void(0)" class="add">+</a>
                                </dd>
                                <dd>
                                    <span class="totalprice">${ele.totalprice}</span>
                                </dd>
                                <dd>
                                    <p><a class="delete" href="javascript:void(0)">移除</a></p>
                                </dd>
                            </dl>
             </div>`;
        let tnum_str = `<a href="javascript:void(0)" >0</a>件`;
        let tprice_str = `<a href="javascript:void(0)">0</a>`
        $("#totalnum").html(tnum_str);
        $("#totalprice").html(tprice_str);
        return str;
    }
    //没有登录时,显示购物车信息
    let showInfo2 = function () {
        let goodlist = JSON.parse($.cookie("carts"));
        // let object = 180, totalmoney = 0, totalnum = 0;
        goodlist.forEach((ele, index) => {
            $(".shop .checkmoney").before(getStr(ele));
            $($(".good")[index]).attr("data-info", JSON.stringify(ele));
        })
        select();
        caculate();
    }

    //登录时时,显示购物车信息
    function showInfo() {
        $.ajax({
            url: "../../server/cart/getCartsByUser.php",
            data: JSON.parse(sessionStorage.getItem("userInfo")),
            type: "post"
        }).then(function (res) {
            //渲染页面
            let totalnum = 0,
                totalmoney = 0,
                object = 180;
            res.forEach((ele, index) => {
                let str = `
                    <div class="good">
                                    <dl>
                                        <dt><input type="checkbox"></dt>
                                        <dd>
                                            <span><a href="#"><img src=${ele.goodpic} alt=""></a></span>
                                            <span class="right">
                                                <p class="description"><a href="#"> ${ele.g_name}（${ele.gid})</a></p>
                                                <p class="brief">品牌：梦芭莎　尺寸：${ele.g_size}　颜色：${ele.g_color} </p>
                                            </span>
                                        </dd>
                                        <dd>
                                            <span>¥${ele.g_price}</span>
                                        </dd>
                                        <dd>
                                            <a href="javascript:void(0)" class="minus">-</a>
                                            <input type="text" class="num" value=${ele.g_num}>
                                            <a href="javascript:void(0)" class="add">+</a>
                                        </dd>
                                        <dd>
                                            <span class="totalprice">${ele.total_price}</span>
                                        </dd>
                                        <dd>
                                           
                                            <p><a class="delete" href="javascript:void(0)">移除</a></p>
                                        </dd>
                                    </dl>
                     </div>`;
                      let tnum_str = `<a href="javascript:void(0)" >0</a>件`;
                      let tprice_str = `<a href="javascript:void(0)">0</a>`
                      $("#totalnum").html(tnum_str);
                      $("#totalprice").html(tprice_str);
                $(".shop .checkmoney").before(str);
                $($(".good")[index]).attr("data-info", JSON.stringify(ele));
                let dif_price = object -= ele.total_price; //差价
                totalnum += ele.g_num;
                totalmoney += ele.total_price;
                if (dif_price <= 0) {
                    $("#dif_mention").remove();
                } else {
                    $("#price_difference").html(dif_price);
                }
            })
            select();
            caculate();
        })
    }

    //全选和反选
    function select() {
        //全选
        $("#all").click(function () {
            $(".shop input[type=checkbox]").prop("checked", this.checked);
        })
        //反选
        $("all").click(function () {
            let oChex = $(".shop input[type=checkbox]");
            for (var i = 0; i < oChex.length; i++) {
                oChex[i].checked = !oChex[i].checked;
            }
        })
        //如果每一个商品都勾选,则给全选框打勾
        $(".shop input[type=checkbox]").click(function () {
            let status = $(".shop input[type=checkbox]:checked").length == $(".shop input[type=checkbox]").length;
            $("#all")[0].checked = status;
        })
    }
    //改变购买的商品数量
    function updateGoodNum() {
        //数量+1
        $(document).on("click", ".add", function (e) {
            let num = JSON.parse($(e.target).parent().children("input[type=text]").val());
            $(e.target).parent().children("input[type=text]").val(num + 1);
            let number = parseInt($(e.target).parent().children("input[type=text]").val());
            let $o = $(e.target).parents(".good");
            let good_id = JSON.parse($o.attr("data-info")).gid;
            let price = JSON.parse($o.attr("data-info")).g_price;
            let size = JSON.parse($o.attr("data-info")).size;
            if ($.cookie("carts")) {
                price = JSON.parse($o.attr("data-info")).price;
                size = JSON.parse($o.attr("data-info")).size;
            }
            //修改数据
            GoodTools.updateGoodByName(good_id, number, price, size);
            $(e.target).parents(".good").find(".totalprice").html((num + 1) * price);
            //如果选择了该项商品,则重新计算总价格
            //找到多选框
        
            let flag = $(e.target).parents(".good").find("input[type=checkbox]")[0].checked;
            if (flag) {
                let totalnum = parseInt($("#totalnum a").html());
                let totalprice = parseInt($("#totalprice a").html());
                let tnum_str = `<a href="javascript:void(0)" >${totalnum+1}</a>件`;
                let tprice_str = `<a href="javascript:void(0)">${parseInt(totalprice)+parseInt(price)}</a>`
                $("#totalnum").html(tnum_str);
                $("#totalprice").html(tprice_str);
                let dif_price = 180 - (totalprice - price);
                if (dif_price <= 0) {
                    dif_price = 0;
                }
                dif_price = `<em id="price_difference">${dif_price}</em>`
                $("#dif_mention").html(dif_price);
            }
        })
        //数量-1
        $(document).on("click", ".minus", function (e) {
            let num = JSON.parse($(e.target).parent().children("input[type=text]").val());
            $(e.target).parent().children("input[type=text]").val(num - 1);
            let number = parseInt($(e.target).parent().children("input[type=text]").val());
            let $o = $(e.target).parents(".good");
            let good_id = JSON.parse($o.attr("data-info")).gid;
            let price = JSON.parse($o.attr("data-info")).g_price;
            let size = JSON.parse($o.attr("data-info")).size;
            if ($.cookie("carts")) {
                price = JSON.parse($o.attr("data-info")).price;
                size = JSON.parse($o.attr("data-info")).size;
            }
            GoodTools.updateGoodByName(good_id, number, price, size);
            $(e.target).parents(".good").find(".totalprice").html((num - 1) * parseInt(price));
            let flag = $(e.target).parents(".good").find("input[type=checkbox]")[0].checked;

            if (flag) {
                let totalnum = $("#totalnum a").html();
                let totalprice = $("#totalprice a").html();
                let tnum_str = `<a href="javascript:void(0)" >${(totalnum-1)}</a>件`;
                let tprice_str = `<a href="javascript:void(0)">${totalprice-parseInt(price)}</a>`
                $("#totalnum").html(tnum_str);
                $("#totalprice").html(tprice_str);
                let dif_price = 180 - (totalprice - price);
                if (dif_price <= 0) {
                    dif_price = 0;
                }
                dif_price = `<em id="price_difference">${dif_price}</em>`
                $("#dif_mention").html(dif_price);
            }
            let num2 = parseInt($("#good_num").val())
            if (num2 <= 1) {
                return;
            }
        })
    }
    //移除一种商品
    function delgood() {
        $(document).on("click", ".delete", function (e) {
            let $o = $(e.target).parents(".good");
            let good_id = JSON.parse($o.attr("data-info")).gid;
            let num = JSON.parse($o.attr("data-info")).g_num;
            let price = parseInt(JSON.parse($o.attr("data-info")).total_price);
            let size = JSON.parse($o.attr("data-info")).g_size;
            if ($.cookie("carts")) {
                size = JSON.parse($o.attr("data-info")).size;
                num = JSON.parse($o.attr("data-info")).num;
                price = parseInt(JSON.parse($o.attr("data-info")).totalprice);
            }
            GoodTools.deleteGoodByID(good_id, size);
            //拿到当前的总数量和总价格
            let flag = $(e.target).parents(".good").find("input[type=checkbox]")[0].checked;
            if (flag) {
                let totalnum = $("#totalnum a").html();
                let totalprice = parseInt($("#totalprice a").html());
                let tnum_str = `<a href="javascript:void(0)" >${totalnum-num}</a>件`;
                let tprice_str = `<a href="javascript:void(0)">${totalprice-price}</a>`
                $("#totalnum").html(tnum_str);
                $("#totalprice").html(tprice_str);
                let dif_price = 180 - (totalprice - price);
                if (dif_price <= 0) {
                    dif_price = 0;
                }
                dif_price = `<em id="price_difference">${dif_price}</em>`
                $("#dif_mention").html(dif_price);
            }

            $o.remove();
        })
    }

    let caculate = function () {
        let num = 0,
            price = 0,
            originprice = 180;
        $(".shop input[type=checkbox]").on("change", function (e) {
            if ($(e.target)[0].checked) {
                let good = $(this).parents(".good");
                let good_id = JSON.parse(good.attr("data-info")).gid;
                let gsize = JSON.parse(good.attr("data-info")).g_size;
                if (JSON.parse(sessionStorage.getItem("userInfo"))) {
                    let obj = {
                        "gid": good_id,
                        "size": gsize,
                        "uid": JSON.parse(sessionStorage.getItem("userInfo")).id
                    }
                    $.ajax({
                        url: "../../server/cart/getCartsByGood.php",
                        data: obj,
                        type: "post"
                    }).then(function (res) {
                        console.log(res);
                        price += res[0].total_price;
                        num += res[0].g_num;
                        let tnum_str = `<a href="javascript:void(0)" >${num}</a>件`;
                        let tprice_str = `<a href="javascript:void(0)">${price}</a>`
                        $("#totalnum").html(tnum_str);
                        $("#totalprice").html(tprice_str);
                        let dif_price = originprice - price;
                        if (dif_price <= 0) {
                            dif_price = 0;
                        }
                        dif_price = `<em id="price_difference">${dif_price}</em>`
                        $("#dif_mention").html(dif_price);
                    })
                } else {
                    //未登录
                    if ($.cookie("carts")) {
                        let gsize = JSON.parse(good.attr("data-info")).size;
                        let cookieList = JSON.parse($.cookie("carts"));
                        cookieList.forEach((ele, index) => {
                            if (ele.gid == good_id && ele.size == gsize) {
                                price += ele.totalprice;
                                num += ele.num;
                                let tnum_str = `<a href="javascript:void(0)" >${num}</a>件`;
                                let tprice_str = `<a href="javascript:void(0)">${price}</a>`
                                $("#totalnum").html(tnum_str);
                                $("#totalprice").html(tprice_str);
                                let dif_price = originprice - price;
                                if (dif_price <= 0) {
                                    dif_price = 0;
                                }
                                dif_price = `<em id="price_difference">${dif_price}</em>`
                                $("#dif_mention").html(dif_price);
                            }
                        })
                    }
                }
            } else {
                console.log(111);
                let good = $(this).parents(".good");
                let good_id = JSON.parse(good.attr("data-info")).gid;
                let gsize = JSON.parse(good.attr("data-info")).g_size;
                if (JSON.parse(sessionStorage.getItem("userInfo"))) {
                    let obj = {
                        "gid": good_id,
                        "size": gsize,
                        "uid": JSON.parse(sessionStorage.getItem("userInfo")).id
                    }
                    $.ajax({
                        url: "../../server/cart/getCartsByGood.php",
                        data: obj,
                        type: "post"
                    }).then(function (res) {
                        price -= res[0].total_price;
                        num -= res[0].g_num;
                        let tnum_str = `<a href="javascript:void(0)" >${num}</a>件`;
                        let tprice_str = `<a href="javascript:void(0)">${price}</a>`
                        $("#totalnum").html(tnum_str);
                        $("#totalprice").html(tprice_str);
                        let dif_price = originprice - price;
                        if (dif_price <= 0) {
                            dif_price = 0;
                        }
                        dif_price = `<em id="price_difference">${dif_price}</em>`
                        $("#dif_mention").html(dif_price);

                    })
                } else {
                    //未登录
                    if ($.cookie("carts")) {
                        let gsize = JSON.parse(good.attr("data-info")).size;
                        let cookieList = JSON.parse($.cookie("carts"));
                        cookieList.forEach((ele, index) => {
                            if (ele.gid == good_id && ele.size == gsize) {
                                price -= ele.totalprice;
                                num -= ele.num;
                                let tnum_str = `<a href="javascript:void(0)" >${num}</a>件`;
                                let tprice_str = `<a href="javascript:void(0)">${price}</a>`
                                $("#totalnum").html(tnum_str);
                                $("#totalprice").html(tprice_str);
                                let dif_price = originprice - price;
                                if (dif_price <= 0) {
                                    dif_price = 0;
                                }
                                dif_price = `<em id="price_difference">${dif_price}</em>`
                                $("#dif_mention").html(dif_price);

                            }
                        })
                    }
                }
                let tnum_str = `<a href="javascript:void(0)" >${num}</a>件`;
                let tprice_str = `<a href="javascript:void(0)">${price}</a>`
                $("#totalnum").html(tnum_str);
                $("#totalprice").html(tprice_str);
            }
        })
    }

    $(function () {
        $("#goTop").click(function () {
            $("html,body").animate({
                scrollTop: 0
            }, 'slow');
        });
        $(".checkmoney").on("click",function(){
            $(".good").remove();
             let tnum_str = `<a href="javascript:void(0)" >0</a>件`;
             let tprice_str = `<a href="javascript:void(0)">0</a>`
             $("#totalnum").html(tnum_str);
             $("#totalprice").html(tprice_str);
        })
        //登录后,就把cookie里的商品加入数据库
        if (sessionStorage.getItem("userInfo") && $.cookie("carts")) {
            let user = JSON.parse(sessionStorage.getItem("userInfo"));
            JSON.parse($.cookie("carts")).forEach((ele, index) => {
                let preObj = ele;
                preObj.uid = user.id;
                preObj.total = preObj.num * preObj.price;
                console.log(preObj);
                $.ajax({
                    url: "../../server/cart/addCart.php",
                    data: preObj,
                    type: "post"
                }).then(function (res) {
                    $.cookie("carts", "", {expires: -1});
                    location.reload();
                })
            });
        } else if (!$.cookie("carts") && sessionStorage.getItem("userInfo")) {
            //登录了
            showInfo();
            delgood();
            updateGoodNum();
            let input = $(".buy_goods input[type=checkbox]")
            for (let i = 0; i < input.length; i++) {
                input[i].checked = true;
            }

        } else if ($.cookie("carts")) {
            //未登录但购买了商品
            showInfo2();
            delgood();
            updateGoodNum();
            let input = $(".buy_goods input[type=checkbox]")
        } else {
            //没有购买任何商品
            $(".mention").show().next("div").css("display", "block").show();
        }
    })
})
(jQuery)